/**
 * FileName: CookieHandler
 * Author: Administrator
 * Date: 2020/12/21 0021 11:00
 * Description:
 */
package com.linkage.linkedlife.retrofit;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

/**
 * @ClassName: CookieHandler
 * @Description: java类作用描述
 * @Author: Clakr
 * @Date: 2020/12/21 0021 11:00
 */
public class CookieHandler {
    private static HashMap<String, HashMap<String, String>> COOKIE_MAP = new HashMap<>(3);

    private static String[] COOKIE_SKIP_KEY = {"domain", "path", "expires", "max-age", "discard"};


    public static void processResponseCookie(Response proceed, String host) {
        //-----------------------------------------------------------------------------------------------------
        // 1、获取响应的Set-Cookie值，得到响应的Cookie字符串集合
        //-----------------------------------------------------------------------------------------------------
        List<String> setCookies = proceed.headers("Set-Cookie");


        if (setCookies == null) {
            return;
        }
        //String cookieStr = "";

        HashMap<String, String> cookieMap = COOKIE_MAP.get(host);
        if (cookieMap == null) {
            cookieMap = new HashMap<>(5);
        }

        for (String str : setCookies) {

            if (str.contains(";")) {
                String[] attrs = str.split(";");
                for (String attr : attrs) {
                    if (attr.contains("=")) {
                        String[] kv = attr.split("=");
                        if (!isSkip(kv[0])) {
                            cookieMap.put(kv[0], kv[1]);
                        }
                    }
                }
            } else {
                if (str.contains("=")) {
                    String[] kv = str.split("=");
                    if (!isSkip(kv[0])) {
                        cookieMap.put(kv[0], kv[1]);
                    }
                }
            }
        }

        COOKIE_MAP.put(host, cookieMap);
    }

    public static String getCookieStr(String host) {
        String cookieStr = "";
        HashMap<String, String> cookieMap = COOKIE_MAP.get(host);

        if (cookieMap != null) {
            Iterator<Map.Entry<String, String>> it = cookieMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                cookieStr += entry.getKey() + "=" + entry.getValue() + ";";
            }
        }
        return cookieStr;
    }

    private static boolean isSkip(String key) {
        for (int i = 0; i < COOKIE_SKIP_KEY.length; i++) {
            if (COOKIE_SKIP_KEY[i].equals(key.toLowerCase().trim())) {
                return true;
            }
        }
        return false;
    }

    public static void clear() {
        COOKIE_MAP.clear();
    }

}